from tools.listNode import ListNode, listToNode, nodeToList


def swapPairs(head):
    if not head:
        return []
    res = ListNode()
    res.next = head
    cur = res
    while cur and cur.next:
        next = head.next
        temp = next.next
        # 交换过程
        cur.next = next
        next.next = head
        head.next = temp
        # 指针后移
        cur = head
        head = head.next
    return res.next


head = listToNode([1, 2, 3, 4])
print(nodeToList(swapPairs(head)))  # [2, 1, 4, 3]
